import {
  msw,
  rest,
  setupWorker,
  response,
  createResponseComposition,
  context,
  compose,
} from 'msw';

import path from 'path-browserify';
// console.log('🚀 ~ file: handlers.ts:4 ~ path:', path);
const runtimeConfig = useRuntimeConfig();

export const handlers: Parameters<typeof setupWorker> = [];

const handlerFiles = import.meta.glob(
  ['./api/**/*.ts', './routes/**/*.ts'],
  {},
);

type T = keyof typeof rest;
const methods = <T[]>[...Object.keys(rest)];

const methodsRegExp = new RegExp(`\\.(${methods.join('|')})$`, 'i');

// const pathRegExp = new RegExp(
//   `^\.(?<url>(\/([^./]*))+)(?<index>(\/index)?)((\.(?<method>${methods.join(
//     '|',
//   )}))?)\.ts$`,
//   'i',
// );

// console.log('🚀 ~ file: handlers.ts:19 ~ pathRegExp:', pathRegExp);
// console.log(
//   '🚀 ~ file: handlers.ts:47 ~ Object.keys ~ runtimeConfig:',
//   runtimeConfig,
// );

const myCustomResponse = createResponseComposition(undefined, [
  context.delay('real'),
]);

Object.keys(handlerFiles).forEach((fileName) => {
  let url = fileName.slice(1, -3);
  // const data = pathRegExp.exec(fileName);
  // console.log('🚀 ~ file: handlers.ts:29 ~ Object.keys ~ data:', data);

  if (url.startsWith('/routes')) {
    url = url.slice(7);
  }

  const method = <T | void>methodsRegExp.exec(url)?.[1];
  if (method) {
    // 文件名包含有method
    url = url.replace(methodsRegExp, '');
  }
  if (url.endsWith('/index')) {
    // 文件名包含有index
    url = url.slice(0, -6);
  }

  // 替换动态路由格式  [id] => :id
  url = url.replaceAll(/\[(.+?)\]/g, ':$1');

  url = path.join(runtimeConfig.app.baseURL, url);
  // console.log(method, url);

  handlers.push(
    rest[method || 'all'](url, async (req, res, ctx) =>
      handlerFiles[fileName]().then((m) =>
        m?.default?.(req, myCustomResponse, ctx),
      ),
    ),
  );
});
